package com.it.travel01.service.impl;


import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.travel01.dao.CategoryDao;
import com.it.travel01.pojo.Category;
import com.it.travel01.service.CategoryService;
import com.it.travel01.vo.ResultInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service("categoryService")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, Category> implements CategoryService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("constant.categoryListkey")
    private String categoryListkey;

    /**
     * 旅游产品分类查询功能实现
     * @return
     */
    @Override
    public ResultInfo findAllCategory() {
//        List<Category> categories = categoryDao.findAllCategory();
//        List<Category> list = this.list();
//        return new ResultInfo(true,list,null);

        //1.先从redis缓存中查询数据
        List<Category> categories = redisTemplate.opsForList().range(categoryListkey, 0, -1);
        if (!CollectionUtils.isEmpty(categories)) {
            //有，则直接返回
            return new ResultInfo(true, categories, null);
        }
            //无，则从数据库查询获取数据，然后保存在redis下，然后再响应客户端
            //List<Category> categories= categoryDao.findAll();
            categories = this.list();
            //保存时，Category务必实现序列化的接口Serializable，否则序列化报错
            redisTemplate.opsForList().leftPushAll(categoryListkey,categories);
            return new ResultInfo(true,categories,null);
    }
}
